package com.example.admin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.entity.SysPermission;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysRolePermission;
import com.example.admin.mapper.SysRoleMapper;
import com.example.admin.service.ISysRolePermissionService;
import com.example.admin.service.ISysRoleService;

/**
 * <p>
 * 系统角色信息表 服务实现类
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

	@Resource(name = "sysRolePermissionService")
	private ISysRolePermissionService rpService;

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean saveRole(SysRole sysRole) {
		if (sysRole.insert()) {
			if (sysRole.getId() == null) {
				throw new RuntimeException();
			} else {
				List<SysPermission> list = sysRole.getPermissions();
				for (SysPermission sysPermission : list) {
					SysRolePermission rp = new SysRolePermission();
					rp.setRoleId(sysRole.getId());
					rp.setResourceId(sysPermission.getId());
					if (!rp.insert()) {
						throw new RuntimeException();
					}
				}
			}
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean updateRole(SysRole sysRole) {
		QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", sysRole.getId());
		if (rpService.remove(queryWrapper)) {
			if (sysRole.insertOrUpdate()) {
				if (sysRole.getId() == null) {
					throw new RuntimeException();
				} else {
					List<SysPermission> list = sysRole.getPermissions();
					for (SysPermission sysPermission : list) {
						SysRolePermission rp = new SysRolePermission();
						rp.setRoleId(sysRole.getId());
						rp.setResourceId(sysPermission.getId());
						if (!rp.insert()) {
							throw new RuntimeException();
						}
					}
				}
			}
		} else {
			throw new RuntimeException();
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean deleteRole(SysRole sysRole) {
		QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", sysRole.getId());
		if (rpService.remove(queryWrapper)) {
			if (!sysRole.deleteById()) {
				throw new RuntimeException();
			}
		} else {
			throw new RuntimeException();
		}
		return true;
	}

	@Override
	public List<SysRole> getRoleList(Integer userId) {
		return this.baseMapper.getRoleList(userId);
	}

}
